<template>
  <el-button title="插入图片" type="info" @click="openForm()" plain icon="Picture"></el-button>
  <el-dialog v-model="isOpenWin" title="图片上传" width="500">
    <file_upload_box :error-handle="imgErrorHandle" :updating-handle="imgUpdatingHandle" :multiple="false"
      :success-handle="imgSuccessHandle" :max-size="2 * 1024 * 1024" :ex-names="['jpg', 'png', 'jpeg', 'gif']">
    </file_upload_box>
  </el-dialog>
</template>
<script setup lang="ts">
import type { DataResponse } from "@/types/commons/DataResponse";
import file_upload_box from "@/views/system/resourcefile/components/file_upload_box.vue";
import { Editor } from "@tiptap/vue-3";
import { ref } from "vue";
import notice from '@/components/msg/CupkNotice';
import Cupk2Request from "@/service/remoteRequests/Cupk2Request";
const props = defineProps({
  editor: {
    type: Editor,
    required: true,
  }
});
const isOpenWin = ref(false);



const imgErrorHandle = (msg: { message: string }) => {
  notice.byError(msg.message);
}
const imgSuccessHandle = (response: DataResponse) => {
  const img = response.data as { id: string, filename: string, title: string };
  console.log('上传成功');
  console.log(img.filename)
  insertImg(Cupk2Request.getFullPath('api/files/download/' + img.id), img.title);
  isOpenWin.value = false;
}
const imgUpdatingHandle = () => {

}


const openForm = () => {
  isOpenWin.value = true;
}


const insertImg = (src: string, title: string, width?: number) => {
  const imgElement = document.createElement('img');
  imgElement.src = src;
  imgElement.alt = title;
  if (width) {
    imgElement.width = width;
  }
  const serializer = new XMLSerializer();
  let imgString = serializer.serializeToString(imgElement);
  imgString = imgElement.outerHTML;
  props.editor!.chain().focus().insertContent(imgString).run();
}

</script>
<style scoped>
/* 样式可以根据需要添加 */
.editor-button-bar .el-button {
  width: 32px;
  height: 32px;
  margin: 1px;
}

.editor-button-bar .el-button {
  width: 32px;
  height: 32px;
  margin: 1px;
  border-color: #f4f4f5;
}

.editor-button-bar .el-dropdown {
  border: 0px solid #f4f4f5;
}
</style>
